package com.ruoyi.project.system.orderhead.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.changeUtils.FTfontChangeUtils;
import com.ruoyi.common.utils.changeUtils.YNDateUtlis;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.client.domain.Client;
import com.ruoyi.project.system.client.service.IClientService;
import com.ruoyi.project.system.orderhead.domain.Orderhead;
import com.ruoyi.project.system.orderhead.ex.NoProductException;
import com.ruoyi.project.system.orderhead.service.IOrderheadService;
import com.ruoyi.project.system.orderhead.vo.RedPrintVo;
import com.ruoyi.project.system.ordertable.domain.Ordertable;
import com.ruoyi.project.system.ordertable.service.IOrdertableService;
import com.ruoyi.project.system.product.domain.Product;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2021-03-28
 */
@Controller
@RequestMapping("/system/orderhead")
public class OrderheadController extends BaseController
{
    private String prefix = "system/orderhead";

    private String orderTable = "system/ordertable";

    @Autowired
    private IOrderheadService orderheadService;
    @Autowired
    private IClientService clientService;

    @Autowired
    private IOrdertableService ordertableService;

    private Integer id;

    private Integer isIndex = 0;

    private Date time;

    @RequestMapping("/changestatu/{id}")
    @ResponseBody
    public AjaxResult orderChangeStatu(@PathVariable  Integer id){
        orderheadService.updateOrderHeadStateById(id);
        return AjaxResult.success("修改成功");
    }

    @RequestMapping("/printSmall/{orderId}")
    @ResponseBody
    public AjaxResult orderHeadPrintSmall(@PathVariable String  orderId,String method){
        Map<String,Object> modelMap=orderheadService.printSmallOrder(orderId);
        return AjaxResult.success(modelMap);
    }

    @RequestMapping("/print/{orderId}")
    public String orderHeadPrint(@PathVariable String orderId,ModelMap modelMap){
        RedPrintVo redPrintVo1 = orderheadService.printerRedOrder(Integer.parseInt(orderId));

        /*处理发货日期封装*/
        String dispatchDate = null;
        try{
            dispatchDate = redPrintVo1.getDispatchDate();
        }catch (Exception e){
            throw new NoProductException(orderId+",该单未添加商品不可打印");
        }
        if(redPrintVo1.getStateOrderHead()==1){
            throw new NoProductException(orderId+",该单已被取消不可打印");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String format = simpleDateFormat.format(DateUtils.parseDate(dispatchDate));
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = simpleDateFormat1.format(DateUtils.parseDate(dispatchDate));
        Calendar today = Calendar.getInstance();
        String dateOutOrder = "";
        try {
            today.setTime(simpleDateFormat1.parse(format1));
            String qian = YNDateUtlis.qian(today);
            dateOutOrder = format+" "+qian;
            redPrintVo1.setDispatchDate(dateOutOrder);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        /*以下封装订单价格繁体*/
        List<Product> itemList = redPrintVo1.getItemList();
        double sumPriceNum = 0;
        for(Product p :itemList){
            double count = p.getCount();
            Double priceProduct = p.getPriceProduct();
            sumPriceNum += count*priceProduct;
        }
        DecimalFormat df =new java.text.DecimalFormat("#.00");
        String format2 = df.format(sumPriceNum);
        redPrintVo1.setSumPriceNum(format2);
        if(format2.contains(".")){
            int split = format2.indexOf(".");
            String substring = format2.substring(0, split);
            String[] strings = FTfontChangeUtils.changeFont(substring);
            redPrintVo1.setSumPrice(strings);
        }else{
            String[] strings = FTfontChangeUtils.changeFont(format2);
            redPrintVo1.setSumPrice(strings);
        }
        int size = itemList.size();
        if(size<7){
            Product p =null;
            for (int i =0;i<7-size;i++){
                p = new Product();
                p.setNameProduct("");
                p.setcName("");
                p.setCount(null);
                itemList.add(p);
            }
        }
        redPrintVo1.setItemList(itemList);
        System.out.println(redPrintVo1);
        modelMap.put("redPrintVo",redPrintVo1);
        return prefix+"/orderdescprint";
    }

    @RequiresPermissions("system:orderhead:view")
    @GetMapping("/{isHome}")
    public String orderhead(@PathVariable("isHome") Integer isHome)
    {
        isIndex = isHome;
        return prefix + "/orderhead";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:orderhead:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Orderhead orderhead)
    {
        startPage();
        if (time != null){
            orderhead.setDateOrderHead(time);
        }
        Integer addtime = 0;
        if(orderhead.getAddStime() != null && orderhead.getAddEtime() != null){
            addtime = 1;
        }else if (orderhead.getAddStime() != null && orderhead.getAddEtime() == null){
            addtime = 2;
        }else if (orderhead.getAddStime() == null && orderhead.getAddEtime() != null){
            addtime = 3;
        }
        Integer apptime = 0;
        if(orderhead.getAppStime() != null && orderhead.getAppEtime() != null){
            apptime = 1;
        }else if (orderhead.getAppStime() != null && orderhead.getAppEtime() == null){
            apptime = 2;
        }else if (orderhead.getAppStime() == null && orderhead.getAppEtime() != null){
            apptime = 3;
        }
        List<Map<String,Object>> list = orderheadService.getOrderList(orderhead.getClientName(),orderhead.getPhoneOne(),
                orderhead.getPhoneTwo(),orderhead.getAddStime(),orderhead.getAddEtime(),orderhead.getAppStime(),orderhead.getAppEtime()
                ,orderhead.getStateOrderHead(), isIndex,orderhead.getIdorderHead(),orderhead.getDateOrderHead(),addtime,apptime,orderhead.getRegionClient());
        for (Map<String,Object> map :list) {
            Double money = orderheadService.countOrderAllMoney(Integer.parseInt(map.get("idorderHead").toString()) );
            map.put("allMoney" , money);
        }
        time=null;
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:orderhead:export")
    @Log(title = "导出订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Orderhead orderhead)
    {
      // List<Orderhead> list = orderheadService.selectOrderheadList(orderhead);
        List<Orderhead> list = orderheadService.exportOrderHeadList(orderhead.getClientName(),orderhead.getPhoneOne(),
               orderhead.getPhoneTwo(),orderhead.getDateOrderHead(),orderhead.getAppointmentDateOrderHead(),orderhead.getStateOrderHead());
        if ( null != list && list.size() > 0){
            for (Orderhead o :list) {
                Double money = orderheadService.countOrderAllMoney(o.getIdorderHead());
                if (money != null){
                    o.setAllMoney(money.toString());
                }
            }
        }
        ExcelUtil<Orderhead> util = new ExcelUtil<Orderhead>(Orderhead.class);
        return util.exportExcel(list, "orderhead");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:orderhead:add")
    @Log(title = "新增订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Orderhead orderhead)
    {
        orderheadService.addOrderHead(orderhead);
        Integer idorderHead = orderhead.getIdorderHead();
        //return toAjax( orderheadService.addOrderHead(orderhead));
       //return orderTable + "/add";
        //添加商品关联表
        for (int i = 0; i < orderhead.getProductIDOrder().length; i++){
            if (null != orderhead.getProductIDOrder()[i] && orderhead.getCountOrders()[i] != null){
                Ordertable ordertable = new Ordertable();
                ordertable.setHeaderIDOrder(idorderHead.longValue());
                ordertable.setProductIDOrder(orderhead.getProductIDOrder()[i].longValue());
                ordertable.setPriceOrder(orderhead.getPrice()[i].longValue());
                ordertable.setCountOrder(orderhead.getCountOrders()[i].longValue());
                ordertableService.insertOrdertable(ordertable);
            }
        }
       return AjaxResult.success(idorderHead+"");
       //return orderTable + "/add" ;
    }

    /**
     * 修改【请填写功能名称】
     */
    @GetMapping("/edit/{idorderHead}")
    public String edit(@PathVariable("idorderHead") Integer idorderHead, ModelMap mmap)
    {
        //Orderhead orderhead = orderheadService.selectOrderheadById(idorderHead);
        Orderhead orderhead = orderheadService.getOrderhead(idorderHead);
        List<Ordertable> ordertableList = ordertableService.getOrdertableByheadId(idorderHead.longValue());
        mmap.put("orderhead", orderhead);
        if(ordertableList.size() <= 0){
            return prefix + "/zeroEdit";
        }else {
            mmap.put("ordertable", ordertableList);
            mmap.put("otSize",ordertableList.size());
            return prefix + "/edit";
        }
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:orderhead:edit")
    @Log(title = "修改订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Orderhead orderhead)
    {
        //修改前数据
        Orderhead orderhead1 = orderheadService.selectOrderheadById(orderhead.getIdorderHead());
        Map<String,Object> oldMap=orderheadService.printSmallOrder(orderhead1.getIdorderHead()+"");
        //更新操作
        //更新客户表
        if(orderhead.getRegionClient()==null||orderhead.getRegionClient()==0){
            return AjaxResult.error("请选择镇区");
        }else{
            Client client = new Client();
            client.setIdClient(orderhead1.getClientIDorderHead().intValue());
            client.setNameClient(orderhead.getClientName());
            client.setPhoneNum1Client(orderhead.getPhoneOne());
            client.setPhoneNum2Client(orderhead.getPhoneTwo());
            client.setRegionClient(orderhead.getRegionClient());
            client.setAddressStreetClient(orderhead.getAddress());
            clientService.updateClient(client);
        }
        //更新订单商品表
        if (orderhead.getProductIDOrder().length > 0){
            ordertableService.delOrdertableByHeadId(orderhead.getIdorderHead().longValue());
            for (int i = 0; i < orderhead.getProductIDOrder().length; i++){
                if (null != orderhead.getProductIDOrder()[i] && orderhead.getCountOrders()[i] != null){
                    Ordertable ordertable = new Ordertable();
                    ordertable.setHeaderIDOrder(orderhead.getIdorderHead().longValue());
                    ordertable.setProductIDOrder(orderhead.getProductIDOrder()[i].longValue());
                    ordertable.setPriceOrder(orderhead.getPrice()[i].longValue());
                    ordertable.setCountOrder(orderhead.getCountOrders()[i].longValue());
                    ordertableService.insertOrdertable(ordertable);
                }
            }
        }
        int i = orderheadService.updateOrderhead(orderhead);
        //修改后数据
        Orderhead orderhead2 = orderheadService.selectOrderheadById(orderhead.getIdorderHead());
        Map<String,Object> newMap=orderheadService.printSmallOrder(orderhead2.getIdorderHead()+"");
        /**
         * 打印修改小票操作
         * oldMap,newMap
         *         modelMap.put("date",dateOutOrder);
         *         modelMap.put("sumPrice",redPrintVo1.getSumPriceNum());
         *         modelMap.put("order",redPrintVo1);
         */
        Map<String,Map> map = new HashedMap();
        map.put("oldMap",oldMap);
        map.put("newMap",newMap);
        return AjaxResult.success("修改成功",map);
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:orderhead:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        //删除订单中间表
        //orderheadService.deleteOrderTableByIds(ids);
        int count = orderheadService.cancellationOrderbyIds(ids);
        AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.SUCCESS,"成功取消"+count+"条订单",ids);
        return ajaxResult;
    }

    /**
     * 订单详细
     */
    @GetMapping("/read/{idorderHead}")
    public String read(@PathVariable("idorderHead") Integer idorderHead)
    {
        id = idorderHead;
        return prefix + "/list";
    }

    @RequiresPermissions("system:orderhead:list")
    @PostMapping("/readlist")
    @ResponseBody
    public TableDataInfo detail()
    {
        List<Map<String, Object>> readList = orderheadService.getReadOrderDataList(id);
        return getDataTable(readList);
    }

    /**
     * 首页添加订单
     * @return
     */
    @GetMapping("/indexAdd")
    public String indexAdd(ModelMap mmap)
    {
       /* Orderhead orderhead = new Orderhead();
        orderhead.setDateOrderHead(new Date());
        orderhead.setStateOrderHead(3l);
        orderheadService.insertOrderhead(orderhead);
        Integer idorderHead = orderhead.getIdorderHead();
        mmap.put("id",idorderHead);*/
        return prefix + "/indexAdd";
    }

    /**
     * 首页新增保存
     */
    @RequiresPermissions("system:orderhead:add")
    @Log(title = "新增订单", businessType = BusinessType.INSERT)
    @PostMapping("/orderPut")
    public String orderPut( Orderhead orderhead)
    {
        orderheadService.addOrderHead(orderhead);
        return orderTable+"/add";
        //return toAjax(orderheadService.addOrderHead(orderhead));
    }

    @RequiresPermissions("system:orderhead:view")
    @GetMapping("/days")
    public String daysOrder()
    {
        return prefix + "/list";
    }

    @RequiresPermissions("system:orderhead:list")
    @PostMapping("/getDays")
    @ResponseBody
    public TableDataInfo daysOrderList()
    {
        List<Orderhead> readList = orderheadService.queryDaysOrder();
        return getDataTable(readList);
    }
    /**
     * 每日订单查询详情打印
     */
    @GetMapping("/getDaysOrderPrintList/{dateOrderHead}")
    @ResponseBody
    public List<String> daysOrderPrintListByDay(@PathVariable("dateOrderHead") String dateOrderHead) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        time = simpleDateFormat.parse(dateOrderHead);
        List<String> list = orderheadService.selectOrderheadPrintIdListByDay(dateOrderHead);
        return list;
    }

    /**
     * 每日订单查询详情
     */
    @GetMapping("/getDaysOrder/{dateOrderHead}")
    public String daysOrder(@PathVariable("dateOrderHead") String dateOrderHead) throws Exception {
        System.out.println(dateOrderHead);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        time = simpleDateFormat.parse(dateOrderHead);
        return prefix + "/orderhead";
    }

}
